package com.tan.simpleweather.ui.weather

import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.tan.simpleweather.R
import com.tan.simpleweather.base.AppDataBase
import com.tan.simpleweather.base.BasePagerAdapter
import com.tan.simpleweather.base.PlaceBean
import com.tan.simpleweather.logic.Repository
import com.tan.simpleweather.utils.MMKVUtils
import kotlinx.android.synthetic.main.activity_list_weather.*
import kotlin.concurrent.thread

class WeatherListActivity : AppCompatActivity() {

    private var fragmentList: ArrayList<Fragment> = ArrayList()
    private var placeList : ArrayList<PlaceBean> = ArrayList()

    private var pagerAdapter:BasePagerAdapter ?= null

    lateinit var weatherFragment: WeatherFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val decorView = window.decorView
        decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        window.statusBarColor = Color.TRANSPARENT

        setContentView(R.layout.activity_list_weather)

        thread {
            placeList = AppDataBase.getDataBase(this).getPlace().queryAll() as ArrayList<PlaceBean>
            intent.extras?.let {
                val from_adapter = it.getBoolean("from_adapter")
                if (from_adapter) {
                    val lng = it.getString("location_lng").toString()
                    val lat = it.getString("location_lat").toString()
                    val name = it.getString("place_name").toString()
                    val address = it.getString("place_address").toString()

                    val placeBean = PlaceBean(name, lng, lat, address)
                    val id =  AppDataBase.getDataBase(this).getPlace().insertPlace(placeBean)

                    placeList.add(PlaceBean(name, lng, lat, address))
                } else {
                    placeList = it.getSerializable("placelist") as ArrayList<PlaceBean>
                }
            }

            placeList.reversed()
            if (placeList.size != 0){
                for (index in 0 until placeList.size){
                    weatherFragment = WeatherFragment.newInstance(this, placeList[index])
                    fragmentList.add(weatherFragment)
                }
            }

            runOnUiThread {
                pagerAdapter = BasePagerAdapter(supportFragmentManager, fragmentList, placeList)
                viewpager.adapter = pagerAdapter
                viewpager.offscreenPageLimit = 5
            }

        }
    }
}